//
//  HHSelectUserSearchResultView.m
//  HHChatKit
//
//  Created by Henry on 2021/8/20.
//

#import "HHSelectUserSearchResultView.h"
#import <HHTool/HHTool.h>
#import "HHSelectUserTableViewCell.h"

@interface HHSelectUserSearchResultView () <UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@end

static NSString * const userIdentifier = @"HHSelectUserTableViewCell";

@implementation HHSelectUserSearchResultView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor hh_whiteColor];
        self.dataArray = [NSMutableArray array];
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    [self addSubview:self.tableView];
}

- (void)reloadData:(NSArray *)data {
    self.dataArray = data.mutableCopy;
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HHSelectUserTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:userIdentifier];
    cell.model = self.dataArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    HHSelectUserModel *model = self.dataArray[indexPath.row];
    if (model.unable) {
        return;
    }
    model.isSelected = _forceSelect ? YES : !model.isSelected;
    if (self.selectedCallback) {
        self.selectedCallback(model);
    }
}

- (UITableView *)tableView {
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.bounds style:UITableViewStylePlain];
        tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tableFooterView = [[UIView alloc] init];
        tableView.backgroundColor = self.backgroundColor;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.rowHeight = [HHSelectUserTableViewCell viewHeight];
        [tableView registerClass:[HHSelectUserTableViewCell class] forCellReuseIdentifier:userIdentifier];
        
        tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;

        _tableView = tableView;
    }
    return _tableView;
}

@end
